const db = require('../db/index')

//加入书籍
exports.setBook = (req,res)=>{
  const bookMessage = req.body
  //加入书籍基本信息
  const sql = `insert into bookmessage set ?`
  //加入书籍图片
  const sql2 =  `insert into bookimg set ?`
  //获取图书id的函数
        db.query(sql2, {
          bookurl:bookMessage.bookImage
        }, function
        (err, results) {
        if (err) return res.json({ status: 1, message: err.message })
          saveData (results.insertId)
        })
    //传多张图片
    // function getbookId (data){
    //   return new Promise((resolve,reject) => {
    //     db.query(sql2, {
    //       bookurl:data
    //     }, function
    //     (err, results) {
    //     if (err) return res.json({ status: 1, message: err.message })
    //       resolve(results.insertId)
    //       console.log(results.insertId,'results.insertId')
    //     })
    //   })
    // }
    // const bookidNum = async _ =>{
    //   const imgUrlList = bookMessage.bookImage.map(async item => {
    //     const imgIdList  = await getbookId(item)
    //     return imgIdList
    //   })
    //    const imgUrl = await Promise.all(imgUrlList)
    //    setTimeout(saveData(imgUrl),1000)
    //    console.log(imgUrl)
    // }
    // bookidNum()
    function saveData (imgUrl) {
      db.query(sql, { 
        bookName:bookMessage.bookName,
        bookAuthor:bookMessage.authorName,
        bookType:bookMessage.type,
        introduction:bookMessage.introduction,
        uploaderName:bookMessage.UploaderName,
        uploaderClass:bookMessage.UploaderClass,
        bookImage:imgUrl,
        uploadTime:bookMessage.UploaderTime,
        bookStatus:bookMessage.bookStatus,
        isLend:bookMessage.isLend,
      }, function
      (err, results) {
      // 执行 SQL 语句失败
      if (err) return res.json({ status: 1, message: err.message })
      // 注册成功
      res.json({ code:200, message: '上传成功！' })
      })
    }
}
// 查询书籍
exports.getBook = (req,res)=>{
  const sql = `select * from bookmessage`
  db.query(sql,function(err,results) {
    if(err) return res.json(err)
    res.json({
        code:200,
        message:'获取成功',
        data:results
    })
})
}

// 选择书籍
exports.chooseBook = (req, res) => {
  const keyword =  req.body
  const sql = `select * from bookmessage where id = ?`
  db.query(sql, keyword.id,function(err,results) {
      if(err) return res.json(err)
      res.json({
          code:200,
          message:'获取成功',
          data:results
      })
  })
}

//删除书籍
exports.deleteBook = (req,res)=>{
  const keyword =  req.body
  const sql = `DELETE from bookmessage where id = ?`
  db.query(sql, keyword.id,function(err,results) {
    if(err) return res.json(err)
    res.json({
        code:200,
        message:'删除成功'
    })
})
}

//筛选书籍
exports.screenBook = (req,res)=>{
  const keyword =  req.body
  const condition1 = keyword.bookName ? 'bookName LIKE "%'+keyword.bookName+'%" and ' : ''
  const condition2 = keyword.authorName ? 'bookAuthor LIKE "%'+keyword.authorName+'%" and ' : ''
  const condition3 = keyword.type ? 'bookType = '+keyword.type+' and ' : ''
  const condition4 = keyword.isLend ? 'isLend = '+keyword.isLend+' and ' : ''
  //condition5用来防止and后面
  const condition5 = 'id is not null'
  const sql = `select * from bookmessage where `+condition1+condition2+condition3+condition4+condition5
  db.query(sql,function(err,results) {
    if(err) return res.json(err)
    var data = JSON.parse(JSON.stringify(results))
    const sql2 = `select bookurl from bookimg where id = ?`
    const imgList = []
    function getImg (id){
      return new Promise((resolve,reject) => {
        db.query(sql2,id,function(err,results) {
          if(err) return res.json(err)
          var img = JSON.parse(JSON.stringify(results))
          resolve(img)
      })
      })
    }
    async function run(){
      for (item of data){
        const url = await getImg(item.bookImage)
        imgList.push(url[0])
      }
      data.forEach((item,index)=>{
        item.bookImage = imgList[index].bookurl
      })
      res.json({
        code:200,
        message:'查找成功',
        data:data
    })
    }
    run()
})
}


//借书
exports.lendBook = (req,res)=>{
  const form =  req.body
  const beginTime = new Date().getFullYear()+'-'+new Date().getMonth()+'-'+new Date().getDate()+' '+new Date().getHours()+':'+new Date().getMinutes()+':'+new Date().getSeconds()
  const sql = `update bookmessage  set ?  where id = ?`
  const sql2 = `insert into bookrecord set ?`
  const sql3 = `update users set lendBookNum = lendBookNum + 1 where id = ?`
  const b = {
    leaseId:form.leaseId,
    leaseName:form.leaseName,
    leaseClass:form.leaseClass,
    leaseTime:form.leaseTime,
    beginTime:beginTime,
    isLend:1
  }
  const c = form.id
  //d对应的就是借书记录表
  const d = {
    bookId:form.id,
    bookName:form.bookName,
    bookAuthor:form.bookAuthor,
    leaseId:form.leaseId,
    leaseName:form.leaseName,
    leaseClass:form.leaseClass,
    leaseTime:form.leaseTime,
    beginTime:beginTime,
    isReturn:0
  }
  const e = form.leaseId

  db.query(sql,[b,c],function(err,results) {
  })
  db.query(sql3,e,function(err,results){
  })
  db.query(sql2,d,function(err,results){
  })
        res.json({
        code:200,
        message:'借书成功'
        })
}

//根据用户id查询已借书籍
exports.getBookById = (req,res)=>{
  const form =  req.body
  const sql = `select * from bookmessage  where leaseId = ?;`
  db.query(sql,form.leaseId,function(err,results) {
    if(err) return res.json(err)
      results.forEach((item,index)=>{
        item.bookImage = item.bookImage.split(',')
      })
      res.json({
        code:200,
        message:'查找成功',
        data:results
    })
  })
}

//用户进行还书
exports.returnBook = (req,res)=>{
  const form =  req.body
  const sql = `select * from bookmessage  where leaseId = ?;`
  db.query(sql,form.leaseId,function(err,results) {
    if(err) return res.json(err)
      results.forEach((item,index)=>{
        item.bookImage = item.bookImage.split(',')
      })
      res.json({
        code:200,
        message:'查找成功',
        data:results
    })
  })
}

//查看借还书记录
exports.bookRecord = (req,res)=>{
  const form =  req.body
  const sql = `select * from bookrecord  where leaseId = ?;`
  db.query(sql,form.leaseId,function(err,results) {
    if(err) return res.json(err)
      res.json({
        code:200,
        message:'查找成功',
        data:results
    })
  })
}


//获取图片
exports.getimg = (req,res)=>{
  const keyword =  req.body
  const sql = `select bookurl from bookimg where id = ?`
  db.query(sql, keyword.id,function(err,results) {
    if(err) return res.json(err)
    res.json({
        code:200,
        message:'获取成功',
        data:results
    })
})
}

//还书
exports.backBook = (req,res)=>{
  const keyword = req.body
  //清空借书人信息
  const sql = `update bookmessage  set ?  where id = ?`
  //用户借书数量自减一
  const sql2 = `update users set lendBookNum = lendBookNum - 1 where id = ?`
  //更改借书记录
  const sql3 = `update bookrecord set ? where bookId = ? and leaseId = ?`
  const returnTime = new Date().getFullYear()+'-'+new Date().getMonth()+'-'+new Date().getDate()+' '+new Date().getHours()+':'+new Date().getMinutes()+':'+new Date().getSeconds()
  const leaseMessage = {
    leaseId:null,
    leaseName:null,
    leaseClass:null,
    leaseTime:null,
    beginTime:null,
    isLend:0
  }
  const bookRecord = {
    returnTime:returnTime,
    isReturn:1
  }
  const userId = keyword.userId
  const bookId = keyword.bookId

  db.query(sql,[leaseMessage,bookId],function(err,results) {
  })
  db.query(sql2,userId,function(err,results){
  })
  db.query(sql3,[bookRecord,bookId,userId],function(err,results){
  })
  res.json({
    code:200,
    message:'还书成功'
    })
}